//
//  HMUserAccpuntViewModel.swift
//  微博
//
//  Created by 程双岐 on 16/9/22.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

class HMUserAccpuntViewModel: NSObject {
    
    static let sharedUserAccountViewModel : HMUserAccpuntViewModel = HMUserAccpuntViewModel()
    
    
    var useraccount: HMUserAccount?{
        
        return HMUserAccount.loadUserAcc()
    }
    
    var isLogin: Bool{
        
        return useraccount != nil
    }
    
    
    var accessToken :String?{
        
        let token = useraccount?.access_token
        
        let expiresDate = useraccount?.expiresDate
        
        if let to = token {
            
            if expiresDate?.compare(Date()) == .orderedDescending {
                return to
            }else{
                return nil
            }
            
        }else{
            return nil
        }
        
        
        
    }
    
    
    
    
    func requsetAccessToken(code : String,callBack:@escaping (Bool)->()) {
        HMNetWorkTools.sharedTool.requsetAccessToKen(code: code) { (response, errer) in
            if errer != nil{
                print("错我\(errer)")
                callBack(false)
                return
            }
            guard let dict = response as? [String : Any]else{
                print("格式不正确")
                callBack(false)
                return
            }
            let accessToken = HMUserAccount(dict: dict)
            
            self.requestUserInfo(userAccount: accessToken, callBack: callBack)

        }
    
    }
    
    func requestUserInfo(userAccount:HMUserAccount,callBack:@escaping (Bool)->()) {
        HMNetWorkTools.sharedTool.requsetUsrtInfo(accessToken: userAccount.access_token!, uid: userAccount.uid) { (response, erreo) in
            
            if erreo != nil{
                callBack(false)
                return
            }
            guard let dict = response as? [String : Any]else{
                callBack(false)
                return
            }
            let name = dict["name"]
            let imageName = dict["avatar_large"]
            
            userAccount.name = name as? String
            userAccount.avatar_large = imageName as? String
            
            userAccount.saveUserAccount()
            callBack(true)
        }
    }
    
    
    

}
